package thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: tao
 * Date: 2023-12-08
 * Time: 17:59
 */

class MyThreadPoolExecutor {
    //存放线程的链表
    List<Thread> list = new ArrayList<>();
    //阻塞队列：存放要执行的任务
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(5);
    //提供submit方法，可以添加任务
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }
    public MyThreadPoolExecutor(int n) {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                while (true) {
                    try {
                        //取出一个任务
                        Runnable runnable = queue.take();
                        //执行任务
                        runnable.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
            list.add(t);
        }
    }
}
public class MyThreadPoolExecutorTest {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPoolExecutor myThreadPoolExecutor = new MyThreadPoolExecutor(4);
        for (int i = 0; i < 1000; i++) {
            //变量捕获
            int n = i;
            myThreadPoolExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行任务:" + n + "，当前线程：" + Thread.currentThread().getName());
                }
            });
        }
    }
}
